import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Subscription, Observable, Subject } from "rxjs";

@Injectable()
export class SignInService {
  public userLoginUrl = "mock-data/user-login-mock.json";
  public subject = new Subject<any>();

  constructor(private httpClient: HttpClient) {}

  public get currentUser(): Observable<any> {
    return this.subject.asObservable();
  }

  public login(): Subscription {
    return this.httpClient.get(this.userLoginUrl).subscribe(
      res => {
        console.log(`login success> ${res}`);
        localStorage.setItem("currentUser", JSON.stringify(res));
        this.subject.next(Object.assign({}, res));
      },
      err => {
        console.log(err);
      },
      () => {
        console.log("login complete");
      }
    );
  }

  public logout(): void {
    localStorage.removeItem("currentUser");
    this.subject.next(Object.assign({}));
  }
}
